using FluentValidation;
using Microsoft.EntityFrameworkCore;
using Zhaoxi.MSACommerce.CategoryService.Core.Entities;
using Zhaoxi.MSACommerce.CategoryService.Infrastructure.Data.Configuration;
using ZhaoXi.MSACommerce.SharedKenel.Messaging;
using ZhaoXi.MSACommerce.SharedKenel.Result;
using ZiggyCreatures.Caching.Fusion;

namespace Zhaoxi.MSACommerce.CategoryService.UseCases.Queries;

public record GetParemetersByCategoryQuery(long CategoryId) : IQuery<Result<List<ParemeterGroupDto>>>;

public class GetParemetersByCategoryQueryValidator : AbstractValidator<GetParemetersByCategoryQuery>
{
    public GetParemetersByCategoryQueryValidator()
    {
        RuleFor(s => s.CategoryId)
            .GreaterThan(0);
    }
}

public class GetParemetersByCategoryQueryHandler(CategoryDbContext  dbContext,IFusionCache  cache)
:IQueryHandler<GetParemetersByCategoryQuery,Result<List<ParemeterGroupDto>>>
{
    public async Task<Result<List<ParemeterGroupDto>>> Handle(GetParemetersByCategoryQuery request, CancellationToken cancellationToken)
    {
        //从缓存中获取参数
        var key = $"{nameof(ParameterKey)} : {request. CategoryId}" ;
        var parameterDto = await cache.GetOrSetAsync<List<ParemeterGroupDto>>(key,
            async token =>
            {
                var parameterGroups = await dbContext.ParameterGroups.AsNoTracking()
                    .Include(group => group.ParameterKeys)
                    .Where(group => group.CategoryId == request.CategoryId)
                    .ToListAsync(token);
        
                return parameterGroups.Select(sg => new ParemeterGroupDto
                {
                    Id = sg.Id,
                    Name = sg.Name,
                    ParameterKeysDto = sg.ParameterKeys.Select(s => new ParameterKeyDto
                    {
                        Id = s.Id,
                        Name = s.Name
                    }).ToList() // 添加 ToList()
                }).ToList();
            },
            options => options.SetDurationInfinite(),
            token: cancellationToken);
        
        if (parameterDto is null||parameterDto.Count==0)return Result.NotFound();
        return Result.Success(parameterDto);
    }
}